package org.idea.qiyu.framework.datasource.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.idea.qiyu.framework.datasource.properties.MultiDataSourceProperties;
import org.idea.qiyu.framework.datasource.properties.MultiPackageDatasourceProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 动态数据源配置
 *
 * @Author linhao
 * @Date created in 11:45 上午 2021/5/25
 */
@EnableConfigurationProperties({MultiDataSourceProperties.class, MultiPackageDatasourceProperties.class})
@Configuration
public class DynamicDatasourceConfiguration {

    @Resource
    private MultiDataSourceProperties multiDataSourceProperties;

    @Bean
    @Primary
    @ConditionalOnMissingBean
    @ConditionalOnClass(MultiDataSourceProperties.class)
    public DataSource dataSource() {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        ConcurrentHashMap<String, DatasourceConfig> datasourceConfigMap = multiDataSourceProperties.getDatasources();
        Map<Object,Object> datasourcesMap = new HashMap(datasourceConfigMap.size());
        for (String datasourceName : datasourceConfigMap.keySet()) {
            //提前初始化各种数据源的信息
            DataSource dataSource = this.createDatasource(datasourceConfigMap.get(datasourceName));
            datasourcesMap.put(datasourceName,dataSource);
        }
        dynamicDataSource.setTargetDataSources(datasourcesMap);
        dynamicDataSource.setDefaultTargetDataSource(datasourcesMap.get(multiDataSourceProperties.getDefaultDatasource()));
        return dynamicDataSource;
    }

    private synchronized DataSource createDatasource(DatasourceConfig datasourceConfig) {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(datasourceConfig.getUrl());
        druidDataSource.setQueryTimeout(3);
        druidDataSource.setUsername(datasourceConfig.getUsername());
        druidDataSource.setDriverClassName(datasourceConfig.getDriver());
        druidDataSource.setPassword(datasourceConfig.getPassword());
        //具体配置
        druidDataSource.setMaxActive(100);
        druidDataSource.setInitialSize(3);
        druidDataSource.setMinIdle(1);
        druidDataSource.setMaxWait(30000);

        //间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒
        druidDataSource.setTimeBetweenConnectErrorMillis(60000);
        return druidDataSource;
    }


}
